package array.generateMatrix;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SpiralOrder
 * @Description TODO
 * @Author lenovo
 * @Date 2023-02-14 19:04
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class SpiralOrder {

    /**
     * 54. 螺旋矩阵
     * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
     * <p>
     * <p>
     * 示例 1：
     * <p>
     * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
     * 输出：[1,2,3,6,9,8,7,4,5]
     *
     * @param matrix
     * @return
     */
    public List<Integer> spiralOrder(int[][] matrix) {

        int start = 1;
        int end = matrix[0].length * matrix.length;
        int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1;

        List<Integer> resultList = new ArrayList<>();
        while (start <= end) {

            if (top <= bottom) {
                for (int i = left; i <= right; i++) {
                    resultList.add(matrix[top][i]);
                    start++;
                }
                top++;
            }

            if (left <= right) {
                for (int i = top; i <= bottom; i++) {
                    resultList.add(matrix[i][right]);
                    start++;
                }
                right--;
            }
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    resultList.add(matrix[bottom][i]);
                    start++;
                }
                bottom--;
            }
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    resultList.add(matrix[i][left]);
                    start++;
                }
                left++;
            }


        }
        return resultList;
    }

    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 2, 3, 4},
                                     {5, 6, 7, 8},
                                     {9, 10, 11, 12}};

        SpiralOrder spiralOrder = new SpiralOrder();
        List<Integer> list = spiralOrder.spiralOrder(matrix);
        for (Integer integer : list) {
            System.out.println(integer);
        }

    }
}